Page({
  data: {
    payment_name: '',
    dataList: [],
    openQrcode: false, // 是否显示二维码模态框
    openImg: false, // 是否显示社保回执模态框
    openImg1: false, // 是否显示公积金回执模态框
    qrcodeImgsrc: '', // 二维码图片路径
    imgsrc: '', // 社保回执图片路径
    imgsrc1: '', // 公积金回执图片路径
    startDate: '', //开始日期
    endDate: '', //结束日期
    queryParams: {
      start_time: '',
      end_time: '',
    },
    dateArray: [
      [],
      []
    ], // 第一个数组存放年份，第二个数组存放月份
    loading: false, // 加载状态
    // 二维码
    openImg: '',
    modalContent: "",
    flag: '',
    content: '',
    openDate: false,
    isFromImagePreview: false,
    isCheckingLogin: true, // 添加登录检查状态标志
    modalFlag: false,
    // 新增：标记页面是否已离开
    hasLeftPage: false
  },

  // 初始化日期选择器
  initDatePicker: function () {
    const years = []
    const months = []

    // 从2025年开始，到当前年份后5年
    const currentYear = new Date().getFullYear()
    const startYear = 2025
    for (let i = startYear; i <= currentYear + 5; i++) {
      years.push(i)
    }

    // 生成月份数组
    for (let i = 1; i <= 12; i++) {
      // 确保月份是两位数
      const month = i < 10 ? "0" + i : "" + i
      months.push(month)
    }

    // 计算默认索引值 - 2025年1月
    const defaultYearIndex = 0 // 2025年是第一个选项，索引为0
    const defaultMonthIndex = 0 // 1月是第一个选项，索引为0

    this.setData({
      dateArray: [years, months],
      startDateIndex: [defaultYearIndex, defaultMonthIndex],
      endDateIndex: [defaultYearIndex, defaultMonthIndex],
      // 可选：设置默认日期值为2025-01
      startDate: "",
      endDate: ""
    })
  },

  // 打开日期选择器
  open_date: function () {
    // 如果没有已选择的日期，则设置默认值
    if (!this.data.startDate) {
      this.setData({
        startDateIndex: [0, 0], // 2025年1月
        startDate: "2025-01"
      })
    }

    if (!this.data.endDate) {
      this.setData({
        endDateIndex: [0, 0], // 2025年1月
        endDate: "2025-01"
      })
    }

    this.setData({
      openDate: true
    })
  },

  // 生命周期函数，监听页面加载
  onLoad: function () {
    // 页面加载时立即检查登录状态
  },

  // 新增：页面隐藏时执行
  onHide: function() {
    // 标记页面已离开
    this.setData({
      hasLeftPage: true
    });
  },

  // 生命周期函数，监听页面显示
  onShow: function () {
    // 如果是从图片预览返回，不重新加载数据
    if (this.data.isFromImagePreview) {
      this.setData({
        isFromImagePreview: false, // 重置标志
      })
      return
    }

    this.checkLoginStatus();

    // 如果页面之前离开过，则清空筛选条件
    if (this.data.hasLeftPage) {
      this.setData({
        startDate: '',
        endDate: '',
        'queryParams.start_time': '',
        'queryParams.end_time': '',
        hasLeftPage: false // 重置标志
      });
    }

    this.getList();
    this.initDatePicker();
  },

  checkLoginStatus() {
    const openid = wx.getStorageSync('openid');
    if (!openid) {
      this.setData({
        flag: 0
      })
    } else if (openid) {
      this.setData({
        flag: 1,
        isCheckingLogin: false
      });
      this.getUserInfo();
      wx.hideLoading();

      return;
    }
  },

  silentLogin() {
    const app = getApp();
    const loginUrl = `${app.globalData.baseUrl}/login/`;

    wx.login({
      success: (res) => {
        if (res.code) {
          const loginUrlWithCode = `${loginUrl}?code=${res.code}`;

          wx.request({
            url: loginUrlWithCode,
            method: 'POST',
            success: (loginRes) => {
              if (loginRes.data && loginRes.data.data.openid) {
                wx.setStorageSync('access_token', loginRes.data.data.access_token);
                wx.setStorageSync('openid', loginRes.data.data.openid);

                this.setData({
                  flag: 1
                });

                const queryParams = {
                  openid: loginRes.data.data.openid
                };
                const doQueryUser = `${app.globalData.baseUrl}/query_user/`;

                wx.request({
                  url: doQueryUser,
                  method: 'GET',
                  data: queryParams,
                  success: (userRes) => {
                    wx.hideLoading();
                    this.setData({
                      isCheckingLogin: false
                    });

                    if (userRes.data.code === 200 && userRes.data.data.length > 0) {
                      if (userRes.data.data[0].card_id) {
                        if (userRes.data.data[0].status == 0 || userRes.data.data[0].status == 3) {
                          this.setData({
                            flag: 2
                          });
                        }
                      } else if (!userRes.data.data[0].card_id) {
                        this.setData({
                          flag: 3
                        });
                      }
                    } else if (userRes.data.code == '500' || userRes.data.error == '用户未找到') {
                      this.setData({
                        flag: 0
                      });
                    }

                    this.getList();
                    this.initDatePicker();
                  },
                  fail: (err) => {
                    wx.hideLoading();
                    this.setData({
                      isCheckingLogin: false
                    });

                    this.getList();
                    this.initDatePicker();
                  }
                });
              } else {
                wx.hideLoading();
                this.setData({
                  flag: 0,
                  isCheckingLogin: false
                });
              }
            },
            fail: (err) => {
              wx.hideLoading();
              const storedOpenid = wx.getStorageSync('openid');
              if (storedOpenid) {
                this.setData({
                  flag: 1,
                  isCheckingLogin: false
                });
                this.getUserInfo();
                this.getList();
                this.initDatePicker();
              } else {
                this.setData({
                  flag: 0,
                  isCheckingLogin: false
                });
              }
            }
          });
        } else {
          wx.hideLoading();
          const storedOpenid = wx.getStorageSync('openid');
          if (storedOpenid) {
            this.setData({
              flag: 1,
              isCheckingLogin: false
            });
            this.getUserInfo();
            this.getList();
            this.initDatePicker();
          } else {
            this.setData({
              flag: 0,
              isCheckingLogin: false
            });
          }
        }
      },
      fail: (err) => {
        wx.hideLoading();
        const storedOpenid = wx.getStorageSync('openid');
        if (storedOpenid) {
          this.setData({
            flag: 1,
            isCheckingLogin: false
          });
          this.getUserInfo();
          this.getList();
          this.initDatePicker();
        } else {
          this.setData({
            flag: 0,
            isCheckingLogin: false
          });
        }
      }
    });
  },

  handleLogin: function () {
    wx.switchTab({
      url: '/pages/information/information'
    });
  },
  
  handleSupplement: function () {
    // wx.switchTab({
    //   url: '/pages/information/information'
    // });
    if (!wx.getStorageSync('modalFlag')) {
      this.setData({
        'modalFlag': true
      })
    } else {
      wx.navigateTo({
        url: '/pages/supplement/supplement'
      });
    }
  },

  privacyBtn: function () {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    });
  },

  closeModal1() {
    this.setData({
      modalFlag: false
    });
  },

  confirmAction1: function () {
    this.setData({
      'modalFlag': false
    })
    wx.setStorageSync('modalFlag', true)
    wx.navigateTo({
      url: '/pages/supplement/supplement'
    });
  },

  protocolBtn: function () {
    wx.navigateTo({
      url: '/pages/protocol/protocol'
    });
  },

  onContextMenu: function () {
    return false;
  },

  onTouchStart: function () {
    return false;
  },

  getStorage: function () {
    try {
      const loginInfo = wx.getStorageSync('openid');
      if (loginInfo) {
        this.setData({
          flag: 1
        });
        this.getUserInfo()
      } else {
        this.setData({
          flag: 0
        });
      }
    } catch (e) {
      this.setData({
        flag: 0
      });
    }
  },

  getUserInfo: function () {
    const openid = wx.getStorageSync('openid');
    if (!openid) {
      this.setData({
        flag: 0,
        isCheckingLogin: false
      });
      return;
    }

    const queryParams = {
      openid: openid
    };
    const app = getApp();
    const doQueryUser = `${app.globalData.baseUrl}/query_user/`;

    wx.request({
      url: doQueryUser,
      method: 'GET',
      data: queryParams,
      success: (res) => {
        this.setData({
          isCheckingLogin: false
        });

        if (res.data.code === 200 && res.data.data.length > 0) {
          if (res.data.data[0].card_id) {
            if ((res.data.data[0].status == 0 || res.data.data[0].status == 3) && openid) {
              this.setData({
                flag: 2
              })
            }
          } else if (!res.data.data[0].card_id) {
            this.setData({
              flag: 3
            })
          }
        } else if (res.data.code == '500') {
          wx.showToast({
            title: res.data.error,
            icon: 'none'
          });
          this.setData({
            flag: 0
          })
        }
      },
      fail: (err) => {
        this.setData({
          isCheckingLogin: false
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 预览图片
  previewImage: function () {
    const imgsrc = this.data.imgsrc
    if (imgsrc) {
      this.setData({
        isFromImagePreview: true,
      })

      wx.previewImage({
        current: imgsrc,
        urls: [imgsrc],
        success: () => {
          console.log("图片预览成功")
        },
        fail: (err) => {
          console.error("图片预览失败", err)
        },
      })
    } else {
      wx.showToast({
        title: "图片加载失败",
        icon: "none",
      })
    }
  },

  stopPropagation: (e) => {
    return false
  },

  onLongPressImage: function (e) {
    const that = this;
    wx.showActionSheet({
      itemList: ['保存图片', '识别二维码'],
      success(res) {
        if (res.tapIndex === 0) {
          that.saveImageToAlbum();
        } else if (res.tapIndex === 1) {
          that.scanQRCode();
        }
      },
      fail(err) {
        console.error("操作取消", err);
      }
    });
  },

  saveImageToAlbum: function () {
    const that = this;
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        wx.getImageInfo({
          src: that.data.imgsrc,
          success(imageInfo) {
            wx.saveImageToPhotosAlbum({
              filePath: imageInfo.path,
              success() {
                wx.showToast({
                  title: '保存成功',
                  icon: 'success'
                });
              },
              fail(err) {
                wx.showToast({
                  title: '保存失败',
                  icon: 'none'
                });
                console.error("保存图片失败", err);
              }
            });
          },
          fail(err) {
            console.error("获取图片信息失败", err);
          }
        });
      },
      fail() {
        wx.openSetting({
          success(settingdata) {
            if (settingdata.authSetting['scope.writePhotosAlbum']) {
              wx.getImageInfo({
                src: that.data.imgsrc,
                success(imageInfo) {
                  wx.saveImageToPhotosAlbum({
                    filePath: imageInfo.path,
                    success() {
                      wx.showToast({
                        title: '保存成功',
                        icon: 'success'
                      });
                    },
                    fail(err) {
                      wx.showToast({
                        title: '保存失败',
                        icon: 'none'
                      });
                      console.error("保存图片失败", err);
                    }
                  });
                },
                fail(err) {
                  console.error("获取图片信息失败", err);
                }
              });
            } else {
              wx.showToast({
                title: '需要授权才能保存图片',
                icon: 'none'
              });
            }
          }
        });
      }
    });
  },
  scanQRCode: function () {
    const that = this;
    wx.scanCode({
      scanType: ['qrCode'],
      success(res) {
        wx.showToast({
          title: '识别成功',
          icon: 'success'
        });
      },
      fail(err) {
        wx.showToast({
          title: '识别失败',
          icon: 'none'
        });
      }
    });
  },

  getList: function () {
    const app = getApp();
    const query_paymentUrl = `${app.globalData.baseUrl}/query_payment_info/`;
    const openid = wx.getStorageSync('openid');


    if (!openid) {
      return;
    }

    const {
      start_time,
      end_time
    } = this.data.queryParams;

    this.setData({
      loading: true
    });

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 模拟 API 请求
    wx.request({
      url: query_paymentUrl,
      method: 'GET',
      data: {
        openid: openid,
        start_time,
        end_time,
      },
      success: (res) => {
        wx.hideLoading();
        this.setData({
          loading: false
        });

        if (res.data.code === 200 && res.data.data.length > 0) {
          this.setData({
            dataList: res.data.data,
            payment_name: res.data.data[0].user_name
          });
        } else if (res.data.data.length <= 0) {
          this.setData({
            dataList: []
          });
        } else {
          wx.showToast({
            title: '网络错误',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();

        console.error('获取支付记录失败', err);
        this.setData({
          loading: false
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none',
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  open_date: function () {
    this.setData({
      openDate: true
    })
  },

  closeModal: function () {
    this.setData({
      openDate: false
    })
  },

  onStartDateChange: function (e) {
    const value = e.detail.value;
    const year = this.data.dateArray[0][value[0]];
    const month = this.data.dateArray[1][value[1]];

    // 格式化为 YYYY-MM
    const formattedDate = `${year}-${month}`;

    const endDate = this.data.endDate;
    if (endDate) {
      if (formattedDate > endDate) {
        wx.showToast({
          title: '开始日期不能大于结束日期',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          startDate: '',
          startDateIndex: ''
        });
        return;
      } else {
        this.setData({
          startDate: formattedDate,
          startDateIndex: value
        });
        this.confirmAction()
      }
    } else {
      this.setData({
        startDate: formattedDate,
      });
    }
  },

  onEndDateChange: function (e) {
    const value = e.detail.value;
    const year = this.data.dateArray[0][value[0]];
    const month = this.data.dateArray[1][value[1]];

    // 格式化为 YYYY-MM
    const formattedDate = `${year}-${month}`;

    const startDate = this.data.startDate;
    if (startDate) {
      if (formattedDate < startDate) {
        wx.showToast({
          title: '结束日期不能小于开始日期',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          endDate: '',
          endDateIndex: ''
        });
      } else {
        this.setData({
          endDate: formattedDate,
          endDateIndex: value
        });
        this.confirmAction()
      }
    } else {
      this.setData({
        endDate: formattedDate,
      });
    }
  },

  clearDate: function () {
    this.setData({
      startDate: '',
      endDate: '',
      'queryParams.start_time': '',
      'queryParams.end_time': '',
    })
  },

  confirmAction: function () {
    this.setData({
      'queryParams.start_time': this.data.startDate,
      'queryParams.end_time': this.data.endDate,
      openDate: false
    })
    this.getList()
  },

  showQrcode: function (e) {
    const app = getApp();
    const doQrcode = `${app.globalData.baseUrl}/get_qrcode/`;
    const item = e.currentTarget.dataset.item; // 获取传递的数据
    if (item.payment_status == 0) {
      wx.request({
        url: doQrcode, // 替换为你的 API 地址
        method: 'GET',
        success: (res) => {
          const processedHtml = res.data.data.content.replace(/<p>/g, '<p style="margin-bottom: 12px;">')
          this.setData({
            openImg: true,
            imgsrc: res.data.data.qr_code_base64,
            modalContent: res.data.data.bank_account,
            content: processedHtml
          });
        },
        fail: () => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });

    }
  },

  copyContent() {
    if (!this.data.modalContent) {
      wx.showToast({
        title: '内容为空，无法复制',
        icon: 'none'
      });
      return;
    }
    wx.setClipboardData({
      data: this.data.modalContent,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },


  hideModal: function () {
    this.setData({
      openImg: false
    });
  },

  showimg: function (record) {
    this.setData({
      openImg: true,
      imgsrc: record.social_security_image,
    });
  },

  showimg1: function (record) {
    this.setData({
      openImg1: true,
      imgsrc1: record.housing_fund_image,
    });
  },

  getStatusText: function (status) {
    const statusMap = {
      0: '未缴费',
      1: '已缴费',
    };
    return statusMap[status] || '未知状态';
  },

  getStatusClass: function (status) {
    const statusClassMap = {
      0: 'unpaid',
      1: 'received',
    };
    return statusClassMap[status] || '';
  },

  closeQrcode: function () {
    this.setData({
      openQrcode: false
    });
  },

  closeImg: function () {
    this.setData({
      openImg: false
    });
  },

  closeImg1: function () {
    this.setData({
      openImg1: false
    });
  },
});